package com.xyzq.cgate.admin.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xyzq.cgate.admin.mapper.RuleMapper;
import com.xyzq.cgate.admin.service.RuleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xyzq.cgate.common.constant.ZkPathConstants;
import com.xyzq.cgate.common.entity.Rule;
import com.xyzq.cgate.common.rule.custom.entity.ComplexRule;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenchen
 * @since 2019-06-11
 */
@Service
public class RuleServiceImpl extends ServiceImpl<RuleMapper, Rule> implements RuleService {

    @Autowired
    private ZkClient zkClient;



    @Override
    public void insertDbAndZk(Rule rule) throws UnsupportedEncodingException {
        this.insert(rule);
        insertRuleDataToZk(rule);
    }

    @Override
    public void updateDbAndZk(Rule rule, EntityWrapper<Rule> entityWrapper) throws UnsupportedEncodingException {
        this.update(rule, entityWrapper);
        insertRuleDataToZk(rule);
    }

    @Override
    public void deleteDbAndZk(EntityWrapper<Rule> entityWrapper, Rule rule) throws UnsupportedEncodingException {
        this.delete(entityWrapper);
        String ruleBottomZkPath = ZkPathConstants.buildBottomRuleZkPath(rule.getPluginName(), rule.getRuleName());
        if (!zkClient.exists(ruleBottomZkPath)) {
            zkClient.deleteRecursive(ruleBottomZkPath);
        }

    }

    @Override
    public void insertRuleDataToZk(Rule rule) throws UnsupportedEncodingException {
        String ruleZkPath = ZkPathConstants.buildRuleZkPath(rule.getPluginName());
        if(!zkClient.exists(ruleZkPath)) {
            zkClient.createPersistent(ruleZkPath, true);
        }
        String ruleBottomZkPath = ZkPathConstants.buildBottomRuleZkPath(rule.getPluginName(), rule.getRuleName());
        if(!zkClient.exists(ruleBottomZkPath)) {
            zkClient.createPersistent(ruleBottomZkPath, true);
        }
        zkClient.writeData(ruleBottomZkPath, rule.getUniquejson());
    }

    @Override
    public void removeAllZkDataByParentPath(String parentPath) {
        if (zkClient.exists(parentPath)) {
            zkClient.deleteRecursive(parentPath);
        }
    }
}